
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JTextPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Paolo
 */
public class ServerComunication implements Runnable{
    JTextPane text;
    private final int porta;
    ServerSocket serverSocket = null;
    Socket socket = null;
    DataInputStream dataInputStream = null;
    DataOutputStream dataOutputStream = null;

    public ServerComunication(JTextPane text, int porta) {
        this.text = text;
        this.porta = porta;
    }

    public void escreve(String s) {
        if(!(text == null))
        text.setText((!(text.getText().isEmpty()) ? text.getText() : "\n") + s + "\n");
        else
            System.out.println("Server"+porta+": "+s);
    }

    //enviar o pacote
    public void envia(String s) throws IOException{
        dataOutputStream.writeUTF(s);
    }

    //receber o pacote
    public String recebe() throws IOException{
        return dataInputStream.readUTF();
    }

    public void iniciaComunicacao(){
        try {
            serverSocket = new ServerSocket(porta,0);
            escreve("Listening :" + porta);
            socket = serverSocket.accept();
            dataInputStream = new DataInputStream(socket.getInputStream());
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            escreve("Problema de IO em: "+porta);
        }
    }

    public void run(){
        iniciaComunicacao();
    }

}

